package com.huxiu;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.model.User;
import com.huxiu.net.responses.BaseResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.ErrorResponseException;
import com.huxiu.utils.Global;
import com.huxiu.utils.JavaScriptinerface;
import com.huxiu.utils.LogUtil;
import com.huxiu.utils.Settings;
import com.huxiu.utils.TextViewUtil;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.umeng.analytics.MobclickAgent;

import java.util.LinkedHashMap;
import java.util.Map;

import static com.huxiu.HuaTiDetailActivity.mJavaScriptinerface;


/**
 * Created by mfp on 15/4/20:上午9:21.
 */
public class SubmitHuatiCommentActivity extends Activity implements OnClickListener {
    @ViewInject(R.id.content)
    protected View content;

    @ViewInject(R.id.background)
    protected View background;

    @ViewInject(R.id.submit_button)
    TextView submitButton;

    @ViewInject(R.id.edit)
    EditText edit;

    @ViewInject(R.id.text_exit)
    TextView text_exit;

    private String hid;

    private String replyname="";

    private String typeArticle;

    private String value;

    private SubmitHuatiCommentActivity instance;

    private String COMMENT_INTENT_VALUE="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        setContentView(R.layout.activity_submit_comment);
        ViewUtils.inject(this);
        instance=this;
        hid = getIntent().getStringExtra(Constants.HUATI_ID_KEY);
        typeArticle = getIntent().getStringExtra("type");
        if(getIntent().hasExtra(Constants.REPLYNAME)){
            replyname=getIntent().getStringExtra(Constants.REPLYNAME);
            value="@"+replyname+":";
        }
        if(getIntent().hasExtra(UmenEvent.COMMENT_INTENT_KEY)){
            COMMENT_INTENT_VALUE= getIntent().getStringExtra(UmenEvent.COMMENT_INTENT_KEY);
        }
        edit.setText(value);
        edit.setSelection(edit.length());
        background.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_CANCEL
                        || event.getAction() == MotionEvent.ACTION_UP) {
                    if (TextUtils.isEmpty(edit.getText().toString())) {
                        background.requestFocus();
                        finish();
                    } else {
                        new Builder(SubmitHuatiCommentActivity.this).setTitle(R.string.content_not_empty)
                                .setPositiveButton(android.R.string.ok,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                background.requestFocus();
                                                finish();
                                            }
                                        }).setNegativeButton(android.R.string.cancel, null).show();
                    }
                }
                return true;
            }
        });
        submitButton.setOnClickListener(this);
        text_exit.setOnClickListener(this);
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (typeArticle.equals("add_postcomment")){
                    Log.e("str", "stuse" + TextViewUtil.isReplyEntity(value, s.toString()));
                    boolean status=TextViewUtil.isReplyEntity(value, s.toString());
                    submitButton.setEnabled(!status);
                    if (!status){
                        submitButton.setTextColor(getResources().getColor(R.color.button_login));
                    } else {
                        submitButton.setTextColor(getResources().getColor(R.color.gray4));
                    }
                }else{
                    if (s.length() >= 1){
                        submitButton.setTextColor(getResources().getColor(R.color.button_login));
                    } else {
                        submitButton.setTextColor(getResources().getColor(R.color.gray4));
                    }
                    submitButton.setEnabled(s != null && s.toString().trim().length() > 0);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
        InputMethodManager imm = (InputMethodManager) edit.getContext().getSystemService(Context
                .INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit_button:
                if (TextUtils.isEmpty(edit.getText().toString().trim())) {
                    Utils.showToast("请输入评论内容");
                    return;
                }
                if(typeArticle.equals(Constants.HUATICOMMENT_ADD)){
                    UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_DETAIL, UmenEvent.TOPIC_DETAIL_REPLY_COMMENT);
                    HuaTiDetailActivity.mJavaScriptinerface.huatiCommentH5(edit.getText().toString().trim());
                    this.finish();
                }else if(typeArticle.equals(Constants.COMMENT_ADD)){
                    submitComment();
                }
                break;
            case R.id.text_exit:
                finish();
                break;
        }
    }



    private void submitComment() {
        String url = (typeArticle.equals(Constants.COMMENT_ADD) ? NetworkConstants.COMMENT_ADD : NetworkConstants
                .COMMENT_ADD);


        Map<String, String> params = new LinkedHashMap<>();
        params.put("id", hid);
        params.put("content", edit.getText().toString());
        GsonRequest<BaseResponse> request = new GsonRequest<>(
                url,
                Method.POST, BaseResponse.class, true, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    Utils.showToast(R.string.submit_comment_success);
                    Intent intent = new Intent(Constants.INTENT_HUATICOMMENT_SUCCESS);
                    LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                    UmengEvent();
                    finish();
                } else {

                    Utils.showToast(response.error.message);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Throwable t = error.getCause();
                if (t instanceof ErrorResponseException) {
                    Utils.showToast(error.getMessage());
                } else {
                    Utils.showToast(R.string.generic_failure);
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        mQueue.start();
    }


    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
        //关闭窗体动画显示
        this.overridePendingTransition(R.anim.activity_colse, 0);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }

    public void UmengEvent(){
        if(COMMENT_INTENT_VALUE.equals(UmenEvent.TOPIC_DETAIL_REPLY_TOPIC)){
            UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_DETAIL, UmenEvent.TOPIC_DETAIL_REPLY_TOPIC);
        }

    }
}
